package org.itboys.mobile.service.mysql.mobile;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.dao.order.SundayOrderProductMapper;
import org.itboys.mobile.dto.SundayCountDto;
import org.itboys.mobile.dto.SundayCountProductDto;
import org.itboys.mobile.dto.order.SundayOrderDto;
import org.itboys.mobile.dto.order.SundayOrderProductDto;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.service.mongo.mobile.SundayMobileAddressService;
import org.itboys.mobile.service.mongo.mobile.SundayMobileCartService;
import org.itboys.mobile.service.mongo.mobile.SundayMobileCountService;
import org.itboys.mobile.service.mongo.mobile.TianJieMobileMemberService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_订单_service_mobile
 */
@Service
public class SundayMobileOrderService extends BaseMySqlService<SundayOrder> {
    @Autowired
    private SundayMobileCountService countService;
    @Autowired
    private TianJieMobileMemberService memberService;
    @Autowired
    private SundayMobileAddressService addressService;
    @Autowired
    private SundayOrderProductMapper orderProductMapper;
    @Autowired
    private SundayProductMapper productMapper;

    @Autowired
    private SundayMobileCartService cartService;
    @Autowired
    private TianJieMobileWalletService walletService;
    /**
     * 提交订单
     * @param memberId
     * @param cartIds
     * @param addressId
     * @param remark
     * @return
     */
    @Transactional
    public Map<String,Object> createOrder(Long memberId,List<Long> cartIds,
                                          Long addressId,String remark){

        Map<String,Object> result = new HashMap<String,Object>();
        
        //返回数据
        String receiveName="";//收获信息
        String receiveMobile="";//收获信息
        String receiveAddress="";//收获信息
       // String payAmount="";//收获信息


        //2获取购物车(结算)数据
        SundayCountDto countDto =countService.countCart(memberId,cartIds,null);
        if(!LongUtil.isNotZreo(addressId)){
                throw new ErrorException("请填写收货地址");
        }
        //收货地址
        SundayAddress address = addressService.getById(addressId);;
        //判断余额是否足够
        if(countDto.getBalance().compareTo(countDto.getPayAmount())!=1){
            throw new ErrorException("当前可用待释放余额不足，可用余额："+countDto.getBalance());
        }
        //扣减月


        //准备订单数据
        SundayOrder order = new SundayOrder();
        TianJieMember member = memberService.getById(memberId);
        order.setOrderNo(NumberUtil.generateNumber("TG"));
        //组装订单
        order.setTotalAmount(countDto.getTotalAmount());
        order.setPayAmount(countDto.getPayAmount());
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DFK);

        order.setReceiveName(address.getReceiveName());
        order.setReceiveMobile(address.getReceiveMobile());
        order.setReceiveAddress(address.getReceiveAddress());
        order.setMemberId(member.getId());
        order.setMemberName(member.getNickName());
        order.setSendAmount(countDto.getSendAmount());
        order.setRemark(remark);
        //保存订单
        super.insert(order);
        //保存售的商品ID
      //  List<Long> productIds=new ArrayList<Long>();
       // //本次销售的商品数量
      //  List<Integer> sale_nums=new ArrayList<Integer>();
        //保持订单商品
        List<SundayOrderProduct> orderProducts = new ArrayList<SundayOrderProduct>();
        for(SundayCountProductDto countProduct:countDto.getProducts()){
            SundayOrderProduct orderProduct = new SundayOrderProduct(
                    order.getId(), countProduct.getPrice(), countProduct.getId(),
                    countProduct.getName(),  countProduct.getNumber(),  countProduct.getImage(),  countProduct.getStandard(), countProduct.getNum());
            orderProductMapper.insert(orderProduct);
            //productIds.add(countProduct.getId());
            //更新产品销量
            SundayProduct product = new SundayProduct();
            product.setId(countProduct.getId());
            product.setSaleNumber(countProduct.getSaleNumber()+countProduct.getNum());
            productMapper.update(product);
        }

        //删除购物车
        cartService.deleteCart(cartIds,memberId,null);
        //2017年12月18日
        //扣减用户余额

        walletService.generateRecord(null,memberId, order.getPayAmount(),SundayCommonConstants.wallet_record_type_mall,"全球购商城消费",0l);

        //组织返回数据
      //  result.put("order",order);
       // result.put("orderProducts",orderProducts);
        result.put("info","返回信息待定");
        return result;
    }


    /**
     * 分页获取订单
     * @param request
     * @param memberId
     * @param status
     * @return
     */
    public List<SundayOrderDto> getOrder(HttpServletRequest request, Long memberId, Integer status){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"orderNo");
        param.put("memberId",memberId);
        if(status!=null&&status!=0){
            param.put("status",status);
        }
        List<SundayOrder> orders = super.select(param);
        return packageDtoBatch(orders);

      //  return orders;
    }
    /**
     * 确认收货
     * @param orderId
     * @param memberId
     */
    @Transactional
    public void confirmReceive(Long orderId,Long memberId){
        if(LongUtil.isNotZreo(memberId)){
            SundayOrder order = super.find(orderId);
            if(order.getOrderStatus()!= SundayCommonConstants.ORDER_STATUS_PSZ){
                throw new ErrorException("订单状态错误，请刷新后重试 !");
            }
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YSH);
            super.update(order);
        }
    }



    public SundayOrderDto packageDtoSingle(SundayOrder order, List<SundayOrderProductDto> products){
        if(ListUtil.isNull(products)){
            Map<String,Object> param =new HashMap<String ,Object>();
            param.put("orderId",order.getId());
            products=new ArrayList<SundayOrderProductDto>();
            for(SundayOrderProduct orderProduct:orderProductMapper.select(param)){
                if(orderProduct.getOrderId().longValue()==order.getId()){
                     products.add(new SundayOrderProductDto(
                            orderProduct.getProductId(),orderProduct.getCreateTime(),orderProduct.getCreateDate(),
                            orderProduct.getPrice(), orderProduct.getName(), orderProduct.getNumber(),orderProduct.getImage(),
                            orderProduct.getStandard(), orderProduct.getNum()));
                }
            }

        }
        String sendTime= order.getSendTime()!=null?TimeUtils.format(order.getSendTime(),"yyyy-MM-dd HH:mm:ss"):null;
        String receiveTime= order.getReceiveTime()!=null?TimeUtils.format(order.getReceiveTime(),"yyyy-MM-dd HH:mm:ss"):null;
        return new SundayOrderDto(order.getId(),order.getCreateTime(),order.getCreateDate(),
                order.getOrderNo(), order.getTotalAmount(), order.getPayAmount(),
                order.getOrderStatus(), order.getReceiveName(),order.getReceiveMobile(), order.getReceiveAddress(),
                order.getSendAmount(), order.getSendCompany(),order.getSendCompanyCode(),order.getSendCode(), order.getRemark(),
                sendTime, receiveTime,  products);

    }
    public List<SundayOrderDto> packageDtoBatch(List<SundayOrder> orders){
        List<SundayOrderDto> dtos= new ArrayList<SundayOrderDto>();
        List<Long> orderIds = new ArrayList<>();
        for(SundayOrder order:orders){
            orderIds.add(order.getId());
        }
        Map<String,Object> param =new HashMap<String ,Object>();
        param.put("orderIds",orderIds);
        List<SundayOrderProduct> orderProducts = orderProductMapper.select(param);
        for(SundayOrder order:orders){
            List<SundayOrderProductDto> ps = new ArrayList<SundayOrderProductDto>();
            for(SundayOrderProduct orderProduct:orderProducts){
                if(orderProduct.getOrderId().longValue()==order.getId()){
                    ps.add(new SundayOrderProductDto(orderProduct.getProductId(),orderProduct.getCreateTime(),orderProduct.getCreateDate(),
                            orderProduct.getPrice(), orderProduct.getName(), orderProduct.getNumber(),orderProduct.getImage(),
                            orderProduct.getStandard(), orderProduct.getNum()));
                }
            }
            dtos.add(packageDtoSingle(order,ps));
        }
        return dtos;
    }

}
